package org.vyana.model.business {
	
	import flash.events.AsyncErrorEvent;
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;
	
	import mx.rpc.Fault;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class LocalConnectionServiceDelegate extends VyanaDelegate {
		
		function LocalConnectionServiceDelegate(responder:IResponder, serviceName:String) {
			super(responder, serviceName);
			
			this.service = context.services.getLocalConnectionService(serviceName);
			
			if (localConnection) {
				localConnection.addEventListener(StatusEvent.STATUS, onCallStatus);
				localConnection.addEventListener(AsyncErrorEvent.ASYNC_ERROR, onAsyncError);
			}
		}
		
		protected function get localConnection():LocalConnection {
			return service ? VyanaLocalConnectionService(service).localConnection : null;
		}
		
		protected function onAsyncError(e:AsyncErrorEvent):void {
			
		}
		
		protected function onCallStatus(e:StatusEvent):void {
			if (localConnection)
				localConnection.removeEventListener(StatusEvent.STATUS, onCallStatus);			
			
			if (e.level == 'status')
				responder.result(ResultEvent.createEvent(e.target));
			
			if (e.level == 'error')
				responder.fault(FaultEvent.createEvent(new Fault(e.code, 'Error invoking local connection method')));
		}
		
	}
}